package org.groupg.practice;

import org.mapdb.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

public class MixedValueTypesExample {
    public static void main(String[] args) {
        DB db = DBMaker.memoryDB().make();

        // 创建混合类型值的映射
        ConcurrentMap<String, Object> metricsMap = (ConcurrentMap<String, Object>) db.hashMap("metrics")
                .valueSerializer(new Serializer<Object>() {
                    @Override
                    public void serialize(DataOutput2 out, Object value) throws IOException {
                        // 序列化逻辑
                        if (value instanceof String) {
                            out.writeUTF("STRING");
                            out.writeUTF((String) value);
                        } else if (value instanceof Integer) {
                            out.writeUTF("INT");
                            out.writeInt((Integer) value);
                        } else if (value instanceof Double) {
                            out.writeUTF("DOUBLE");
                            out.writeDouble((Double) value);
                        } else {
                            throw new IOException("Unsupported type");
                        }
                    }

                    @Override
                    public Object deserialize(DataInput2 in, int available) throws IOException {
                        String type = in.readUTF();
                        switch (type) {
                            case "STRING": return in.readUTF();
                            case "INT": return in.readInt();
                            case "DOUBLE": return in.readDouble();
                            default: throw new IOException("Unknown type");
                        }
                    }
                })
                .createOrOpen();

        // 添加不同类型的值
        metricsMap.put("user_count", 1250); // 整数
        metricsMap.put("conversion_rate", 0.0345); // 双精度
        metricsMap.put("status", "active"); // 字符串

        // 读取并打印值
        System.out.println("User Count: " + metricsMap.get("user_count"));
        System.out.println("Conversion Rate: " + metricsMap.get("conversion_rate"));
        System.out.println("Status: " + metricsMap.get("status"));

        db.close();
    }
}
